package com.shanghaionstar.user;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;

import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.MoreActivity;

import java.io.File;
import java.util.Date;

/**
 * Created by Mengzhou Gu on 2016/8/9.
 */
public abstract class WithActionSheetActivity extends BaseActivity implements ActionSheet.ActionSheetListener {
    private static final int CAMERA = 0x01;
    private static final int PICTURE = 0x02;
    private static final int CROP = 0x03;
    private final static int DEF_HEIGHT = 185;
    private final static int DEF_WIDTH = 185;
    private static Uri mUri;
    private int mWhat;
    private String PHOTO_FILE_NAME = "temp_photo.jpg";
    public static final int SHOW_ACTIONSHEET = 0x100;
    public static final int SHOW_ACTIONSHEET_FEEDBACK = 0x101;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.ActionSheetStyleIOS7);
    }

    /**
     * 显示ActionSheet表单
     */
    public void showDialogToTakeChoosePicture(int what) {
        this.mWhat = what;
        ActionSheet.createBuilder(this, getSupportFragmentManager()).setCancelButtonTitle(getString(R.string.cancel))
                .setOtherButtonTitles(getString(R.string.option_take_photo), getString(R.string.option_open_album))
                .setCancelableOnTouchOutside(true).setListener(this).show();
    }


    @Override
    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

    }

    @Override
    public void onOtherButtonClick(ActionSheet actionSheet, int index) {
        switch (index) {
            case 0:
                exeTakePhoto();
                break;
            case 1:
                exeOpenAlbum();
                break;
            default:
                break;
        }
    }

    /*
   * 从相机获取
   */
    public void exeTakePhoto() {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            PHOTO_FILE_NAME = new Date().getTime() + "_temp_photo.jpg";
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
        }
        startActivityForResult(intent, CAMERA);
    }

    /**
     * 打开相册
     */
    protected void exeOpenAlbum() {
        Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
        pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/png;image/jpg;image/jpeg");
        startActivityForResult(pickIntent, PICTURE);
    }

    private boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CAMERA:
                    if (mWhat == MoreActivity.SHOW_ACTIONSHEET_FEEDBACK) {
                        handlePicData(data, CAMERA);
                    } else {
                        cropOnCamera();
                    }
                    break;
                case PICTURE:
                    if (null != data) {
                        if (mWhat == MoreActivity.SHOW_ACTIONSHEET_FEEDBACK) {
                            handlePicData(data, PICTURE);
                        } else {
                            Uri uri = data.getData();
                            crop(uri, DEF_WIDTH, DEF_HEIGHT);
                        }
                    }
                    break;
                case CROP:
                    handleCropData();
                    break;

                default:
                    break;
            }
        }

    }

    private void cropOnCamera() {
        if (hasSdcard()) {
            File tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
            crop(Uri.fromFile(tempFile), DEF_WIDTH, DEF_HEIGHT);
        } else {
            Toast.makeText(WithActionSheetActivity.this, R.string.onstar_no_sdcard, Toast.LENGTH_SHORT).show();
        }
    }

    public  Bitmap getBitmapFromUri(Uri uri, Context mContext) {
        try {
            // 读取uri所在的图片
//            Bitmap bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), uri);
            String path = getImgPath(uri);
            Bitmap bitmap = FeedBackBitmapUtil.createImageThumbnail(path);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    protected void handleCropData() {
        try {
            Bitmap photo = getBitmapFromUri(mUri, WithActionSheetActivity.this);
            String extension = "png";
            try {
                String filePath = getAbsoluteImagePath(mUri);
                if (filePath != null) {
                    extension = filePath.substring(filePath.lastIndexOf(".") + 1);
                }
            } catch (Exception e) {
                e.printStackTrace();
                extension = "png";
            }
            processSelectedPhoto(photo, extension);
        } catch (Exception e) {
        }
    }


    private void handlePicData(final Intent data, final int type) {
        final Intent _data = data;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (type == PICTURE) {
                        Uri originalUri = _data.getData();
                        mUri = originalUri;
                        if (mUri == null)
                            return;
                        String path = getImgPath(mUri);
                        processSelectedPhoto(path);
                    } else if (type == CAMERA) {
                        File tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
                        mUri = Uri.fromFile(tempFile);
                        String path = tempFile.getAbsolutePath();
                        processSelectedPhoto(path);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private String getImgPath(Uri originalUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        //好像是Android多媒体数据库的封装接口，具体的看Android文档
//        Cursor cursor = managedQuery(originalUri, proj, null, null, null);
        Cursor cursor = getContentResolver().query(originalUri, proj, null, null, null);
        if (cursor != null) {
            //按我个人理解 这个是获得用户选择的图片的索引值
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            //将光标移至开头 ，这个很重要，不小心很容易引起越界
            cursor.moveToFirst();
            //最后根据索引值获取图片路径
            String path = cursor.getString(column_index);
            return path;
        }else {
            return originalUri.getPath();
        }
    }

    private void crop(Uri uri, int width, int height) {
        mUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", width);
        intent.putExtra("outputY", height);
        //        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        //        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, CROP);
    }


    /**
     * @param uri
     * @return 根据uri获取后缀名称
     */
    @SuppressWarnings("deprecation")
    protected String getAbsoluteImagePath(Uri uri) {
        // can post image
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, proj, // Which columns to return
                null, // WHERE clause; which rows to return (all rows)
                null, // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    protected abstract void processSelectedPhoto(Bitmap bitmap, String extension);

    protected abstract void processSelectedPhoto(String path);
}
